package org.anti996.bankms.controller;


import org.anti996.bankms.dao.UserDao;
import org.anti996.bankms.model.Card;
import org.anti996.bankms.util.IOUtil;
import org.anti996.bankms.util.MessageUtil;
import org.anti996.bankms.view.UserCardChooseView;

import java.util.List;

public class UserTransferMoneyController extends ControllerBase {
    private final List<Card> cards_;
    private final UserCardChooseView userCardChooseView_;

    public UserTransferMoneyController(List<Card> cards) {
        super(null);
        cards_ = cards;
        userCardChooseView_ = new UserCardChooseView(cards);
    }

    @Override
    public void deal() {
        super.deal();
        MessageUtil.title("转账");
        MessageUtil.infoln("选择转出卡");
        userCardChooseView_.show();
        MessageUtil.info("请输入您的选择：");
        int choose = IOUtil.parseOrder();
        if (choose < 1 || cards_.size() < choose) {
            wrongInputAndRetry();
            return;
        }
        Card card_from = cards_.get(choose - 1);
        MessageUtil.infoln("选择转入卡（默认本账户）");
        String[] ways = {"转入本账户下的卡", "转入他人账户下的卡"};
        MessageUtil.itemList(ways);
        MessageUtil.info("请输入您的选择：");
        choose = IOUtil.parseOrder();
        Card card_to = null;
        int card_to_id = -1;
        if (choose == 2) {
            MessageUtil.info("输入卡号：");
            card_to_id = Integer.parseInt(IOUtil.parseInput());  // TODO 错误处理
        } else {
            userCardChooseView_.show();
            MessageUtil.info("请输入您的选择：");
            choose = IOUtil.parseOrder();  // TODO 错误处理
            card_to = cards_.get(choose - 1);
            card_to_id = card_to.getId();
        }
        if (card_to_id == -1) {
            MessageUtil.error("错误转入卡号");
            return;
        }
        MessageUtil.info("输入转账金额：");
        double money = Double.parseDouble(IOUtil.parseInput());  // TODO 错误处理
        if (money <= 0) {
            MessageUtil.error("转账金额不能小于0");
        } else {
            boolean result = UserDao.transferMoney(card_from, card_to_id, money);
            if (result) {
                MessageUtil.success("转账成功");
                card_from.setBalance(UserDao.getCardById(card_from.getId()).getBalance());
                if (card_to != null)
                    card_to.setBalance(UserDao.getCardById(card_to.getId()).getBalance());
            } else {
                MessageUtil.error("转账失败");
            }
        }
        Navigator.pop();
        waitForKeyPress();
    }
}
